erpnext.PackingListItems = class PackingListItems {
    constructor(frm,item,callback) {
      this.frm = frm;
      this.item = item;
      this.bundle=this.item.packing_list_items
      this.callback = callback;
      this.make();
      this.render_data();
    }
  
    make() {
      const label=__("Packing List Items");
      const primary_label=this.item.packing_list_items? __("Update") : __("Add");
      this.dialog = new frappe.ui.Dialog({
          title: this.item.marks_no? this.item.marks_no+" "+label:label,
          fields: this.get_dialog_fields(),
          size: 'extra-large',  // small, large, extra-large 
          primary_action_label: primary_label,
          primary_action: () => this.update_bundle_entries(),
      });
  
      this.dialog.show();

      if(this.frm.doc.docstatus==2){
        this.dialog.$wrapper.find('.modal-footer').hide();
        this.dialog.$wrapper.find('.grid-buttons').hide();
        
      }

      if ('total_amount_paid' in this.frm.doc || 'is_freeze' in  this.frm.doc) {
        if(this.frm.doc.total_amount_paid > 0 || this.frm.doc.is_freeze === 1) {
            this.dialog.$wrapper.find('.modal-footer').hide();
            this.dialog.$wrapper.find('.grid-buttons').hide();
            
        }

      }
      if(this.frm.doc.docstatus==1){
        this.dialog.$wrapper.find('.grid-buttons').hide();
      } 
          // 获取窗口高度和宽度  
        let windowHeight = $(window).height();  
        this.dialog.$wrapper.find('.modal-dialog').css('margin-top', windowHeight*3/10 + 'px')
  
    }
  
    get_dialog_fields() {
          // 定义一个对象
          let unit_weights = {};     
          // 保存值的函数，如果值已经存在则不保存
          function saveValue(obj, key, value) {
            if (!obj[key]) {
              obj[key] = value;
            }
          }
          
          // 取出对象中的值
          function getValue(obj, key) {
            return obj[key];
          }



          let fields = [];
          let obj=this;
          let read_only=0;
          
          if(this.frm.doc.docstatus==1 || this.frm.doc.docstatus==2){
            read_only=1;
          }
          fields.push({
                  fieldname: 'entries',
                  fieldtype: 'Table',
                  allow_bulk_edit: true,
                  data: [],
                  fields: [
                      {
                      fieldtype: "Link",
                      options: "Item",
                      fieldname: "item_code",
                      label: __("Item"),
                      read_only:read_only,
                      in_list_view: 1,
                      columns:1,
                      change:function(){                    
                        // console.log(this.get_value())
                        const item_code = this.grid_row.on_grid_fields_dict.item_code.get_value();
                        // let array=obj.dialog.fields_dict.entries.df.data                    
                        frappe.db.get_value("Item",item_code,["stock_uom","item_name","custom_size","custom_unit_weight"]).then((r)=>{
                          this.grid_row.on_grid_fields_dict.item_name.set_value(r.message.item_name);
                          this.grid_row.on_grid_fields_dict.stock_uom.set_value(r.message.stock_uom);
                          this.grid_row.on_grid_fields_dict.size.set_value(r.message.custom_size);
                          // this.grid_row.on_grid_fields_dict.qty.set_value(r.message.custom_unit_weight);
                          saveValue(unit_weights,item_code,r.message.custom_unit_weight)
                        });

                      }
                     },
                     {
                      fieldtype: "Data",
                      fieldname: "item_name",
                      label: __("Item Name"),
                      in_list_view: 1,
                      columns:2,
                      read_only:read_only
                     }, 
                     {
                      fieldtype: "Link",
                      options: "UOM",
                      fieldname: "stock_uom",
                      label: __("UOM"),
                      in_list_view: 1,
                      columns:1,
                      read_only:read_only
                     }, 
                     {
                      fieldtype: 'Float',
                      fieldname: 'qty',
                      label: __('Quantity'),
                      in_list_view:1, 
                      columns:1,
                      default:1,
                      read_only:read_only,
                      change:function(){
                        const qty = this.grid_row.on_grid_fields_dict.qty.get_value();
                        const item_code = this.grid_row.on_grid_fields_dict.item_code.get_value();
                        this.grid_row.on_grid_fields_dict.net_weight.set_value(qty*getValue(unit_weights,item_code) || 0.0);
                      }
                  },
                  {
                      fieldtype: 'Currency',
                      fieldname: 'rate',
                      label:  __('Rate')+'('+__(this.frm.doc.currency)+')',
                      in_list_view:1,
                      columns:1,
                     
                  }, 
                  {
                   fieldtype: 'Float',
                   fieldname: 'net_weight',
                   label: __('Net Weight'),
                   in_list_view:1, 
                   columns:1,
                   
                },
                {
                  fieldtype: "Data",
                  fieldname: "size",
                  label: __("Size"),
                  in_list_view:1, 
                  columns:1,
                  read_only:read_only
                },
                {
                  fieldtype: "Data",
                  fieldname: "customs_item_code",
                  label: __("Customs Item Code"),
                  in_list_view:1, 
                  columns:1,
                 
                },
                {
                  fieldtype: "Data",
                  fieldname: "row_id",
                  label: __("row_id"),
                  read_only:1,
                }

              ]
              
          });
  
          return fields;
      }
  
      update_bundle_entries() {
          let entries = this.dialog.get_values().entries;
      
  
          if ((entries && !entries.length) || !entries) {
              frappe.throw(__("Please add atleast one item in the list"));
          }
  
  
          frappe.call({
          		method: "zy_packlist.zy_packlist.doctype.packing_list.packing_list.add_packing_items_ledgers",
          		args: {
          			entries: entries,
          			child_row: this.item,
          			doc: this.frm.doc
          		},
          	})
          	.then((r) => {
          		this.callback && this.callback(r.message);

              if(this.frm.doc.docstatus==0){
                this.frm.save();
              }else if(this.frm.doc.docstatus==1){
                this.frm.save('Update');
              }
          		
          		this.dialog.hide();
          	});
      }
  
      render_data() {
        if (this.bundle || this.item.old_packing_list_items) {
          frappe
            .call({
              method: "zy_packlist.zy_packlist.doctype.packing_list.packing_list.get_packing_items_ledgers",
              args: {
                name: this.bundle || this.item.old_packing_list_items,
              },
            })
            .then((r) => {
              if (r.message) {
                this.set_data(r.message);
              }
            });
        }
      }


      set_data(data) {
        if(data){
            data.forEach((d) => {
              this.dialog.fields_dict.entries.df.data.push(d);
            });
        
            this.dialog.fields_dict.entries.grid.refresh();
        }

      }
  
  }





  erpnext.PackingListFile = class PackingListFile {
    constructor(method,callback) {
      this.method = method;
      this.callback = callback;
      this.make();
    }

    make() {
      const label=__("Packing List Import");
      this.dialog = new frappe.ui.Dialog({
          title: label,
          fields: [
                  {
                    fieldtype: "Button",
                    fieldname: "download_excel",
                    label: __("Download Excel Template"),
                    click: () => {
                      frappe.db.get_value('File',{'file_name':'PackListTemplateFile.xlsx'},['file_url'])
                        .then((r)=>{
                          if(r.message.file_url){
                              let file_url =r.message.file_url;
                              window.open(file_url);
                          }
                        })
                              
                     },
                  },
                  {
                    fieldtype: "Column Break",
                  },
                  {
                    fieldtype: "Attach",
                    fieldname: "attach_data_excel",
                    label: __("Attach XLSX File"),
                    onchange: () => this.upload_xlsx_file(),
                  },
                ],
          size: 'large',  
      });
      this.dialog.show();
        // 获取窗口高度和宽度  
        let windowHeight = $(window).height();  
        this.dialog.$wrapper.find('.modal-dialog').css('margin-top', windowHeight*3/10 + 'px')
    };

    upload_xlsx_file() {
   
        const file_path = this.dialog.get_value("attach_data_excel");

        let templateString = (file_path || '').toString(); 
          
        if(templateString && templateString.endsWith(".xlsx")){
              frappe.call({
                method: this.method ,
                args: {
                  file_path: file_path
                },
                callback: (r) => {
                  this.callback && this.callback(r.message);
                  this.dialog.hide();
                },
              });
      }else{
            frappe.throw(__("File must be a .xlsx file"));
      }
  }
  };



  erpnext.disply_items = function (head_data, body_data,merge_arry) {
    // let head_data=[[__('Marks No.'), 'Item code', 'Descriptions', 'Size/pc (INCH)','Quantities','UOM','Rate','Amount','Net Weight(Kg)/ Sets','Net Weight(Kg)','Gross Weight(Kg)','CTNS','Carton Measure (CM)']]
    let data=[...head_data, ...body_data]
    // console.log(data);

    $('#item_info_html_grid').empty();

    function calculateMergeCells(data, columnIdexs) {
        let mergeCells = [];
        let preValue = null;
        let startRow = 0;
    
        data.forEach((row, rowIndex) => {
            if (rowIndex === 0) return;        
            let currentRowValue = columnIdexs.map(columnIdex => row[columnIdex]).join('');
    
            if (currentRowValue !== preValue) {
                if (preValue !== null) {
                    columnIdexs.forEach(columnIdex => {
                        mergeCells.push({ row: startRow, col: columnIdex, rowspan: rowIndex - startRow, colspan: 1 });
                    });
                }
                preValue = currentRowValue;
                startRow = rowIndex;
            }
        });      
        // 添加最后一组的合并
        if (preValue !== null) {
            columnIdexs.forEach(columnIdex => {
                mergeCells.push({ row: startRow, col: columnIdex, rowspan: data.length - startRow, colspan: 1 });
            });
        }
        return mergeCells;
    };

    const container = document.querySelector('#item_info_html_grid');

    //    let data= [  
    //     [__('Marks No.'), 'Alumibras code', 'Descriptions', 'Size/pc (INCH)', 'NCM','Quantities','Net Weight(Kg)/ Sets','Net Weight(Kg)','Gross Weight(Kg)','CTNS','Carton Measure (CM)'],  
    //     ['HYQ-1 SA230603946',	'M6S02',	'FRONT TOUCH SCREEN AND LCD DISPLAY M6S02',	6.1 ,	'8517.79.00',	199,	15.084 ,	29.21,	33.35,	1,	'60*46*38'],
    //     ['HYQ-1 SA230603946',	'M70G1', 'FRONT TOUCH SCREEN AND LCD DISPLAY M70G1',	6.2 ,	'8517.79.00',	96,	5.050 ,	29.21,	33.35,	1	,'60*46*38'],
    //     ['HYQ-2 SA230603946',	'M6EI2',  'FRONT TOUCH SCREEN AND LCD DISPLAY M6EI2',	6.1,	'8517.79.00',	199,	15.184 ,	34.47,	37.65,	1,	'60*46*38'],
    //     ['HYQ-2 SA230603946',	'S02AS',  'FRONT TOUCH SCREEN AND LCD DISPLAY S02AS',	6.5 ,	'8517.79.00',	373,	19.284, 	34.47,	37.65,	1,	'60*46*38']
    //     ]
        const hot = new Handsontable(container, {  
            data:data,  
            rowHeaders: true,  
            colHeaders: true,  
            autoColumnSize:true,
            height: 'auto',  
            autoWrapRow: true,  
            autoWrapCol: true,  
            manualColumnResize:true,
            manualRowResize:true,
            manualColumnFreeze:true,
            licenseKey: 'non-commercial-and-evaluation', // for non-commercial use only  
            readOnly:true,
            mergeCells:calculateMergeCells(data,merge_arry),   //[0,9,10,11,12]),
            customBorder:true,
            className: 'htLeft htMiddle',
            rowHeights:26,
        });  
        console.log(data.length);
        $('#item_info_html_grid').css('height',( data.length+1)*50+'px');
  };



  erpnext.customer_address_display = function(frm, address_field, display_field) {

    if (!address_field) {
      if (frm.doctype != "Purchase Order" && frm.doc.customer) {
        address_field = "customer_address";
      } else if (frm.doc.supplier) {
        address_field = "supplier_address";
      } else
        return;
    }
    if (!display_field)
      display_field = "address_display";
    if (frm.doc[address_field]) {
      frappe.call({
        method: "frappe.contacts.doctype.address.address.get_address_display",
        args: { address_dict: frm.doc[address_field] },
        callback: function(r) {
          if (r.message) {
            frm.set_value(display_field, r.message);
          }
        }
      });
    } else {
      frm.set_value(display_field, "");
    }
  };